package gen.tools.delivery;

import gen.tools.Widgets;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.tmatesoft.svn.core.io.SVNRepository;

import com.google.gson.Gson;

public class Deliver4SDEL_3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Deliver4SDEL_3() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		/*
		 * 1. 寫入需求
		 * 2. 記錄F部署
		 * 3. 記錄部署計劃
		 * 3. 將檔案寫入SVN CM OL 封裝檔 
		 * 4. 記錄交付事件
		 * 5. 簽入分公司的SVN Repo
		 * 6. 記錄"SVN交付記錄"
		 * 
		 **/
		
		
		Fod fod = new Gson().fromJson( request.getParameter("fOrderDeliver"), Fod.class);
		String empId = request.getParameter("empId");
		String empName = request.getParameter("empName");
		String subsysId = request.getParameter("subsysId");
		String svnUrl = request.getParameter("svnUrl");
		String svnId = request.getParameter("svnId");
		String svnPwd = request.getParameter("svnPwd");
		
		
		int targetSystemId = wid.getParNumberFromRequest( request.getParameter("targetSystemId") );	//這帳程式在帳務所執行，而3是北區分公司
		
		String sql = "";

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		SVNRepository souRepo = null;
		InputStream ins = null;
		
		String res ="OK";
		int localSystemId = Integer.parseInt( request.getParameter("localSystemId") );
		String localSystemName = request.getParameter("localSystemName");
		
		String msgBody = "";		
		try {
			conn = wid.getConn();
			msgBody = "<font face='微軟正黑體'>Dear all,<p>fORDER 系統<br>";
			msgBody += "您好<p>"+localSystemName+"的&nbsp;"+empName+"&nbsp;產生了交付通知!<p> ";	//信件內容
			
			//記錄部署計劃<研究院>
			int localDeplMainSN = wid.getCurrentSN("deplmain"); //目前部署計劃的流水號
			int tarDeplMainSN = 0; //目前部署計劃的流水號
			sql ="INSERT INTO deplmain (deplmainSN,sysSN,creator,createdDateTime,subsysid,tarDeplmainSN) VALUES (?,?,?,?,?,?)";
			
			ps = conn.prepareStatement( sql );
			ps.setInt(1, localDeplMainSN);
			ps.setInt(2, localSystemId);
			ps.setString(3, empId);
			ps.setTimestamp(4, wid.cDT() );
			ps.setString(5, subsysId );
			ps.setInt(6,tarDeplMainSN);
			ps.execute();
			ps.close();
			
			//產生交付事件<研究院>
			int deliverySN = wid.getCurrentSN("deltask");	//取得交付事件的流水號
			int tarDeliverySN = 0;	//取得交付事件的流水號
			sql = "INSERT INTO deltask (deliverySN,isDeliver,deliveryComment,deliveryTarSN,deplmainSN,souSysSN,tarSysSN,statusSN) VALUES ("+deliverySN+",?,?,?,?,?,?,?)";
			ps = conn.prepareStatement( sql );
			ps.setString(1,"t");
			ps.setString(2, fod.getComment() );
			ps.setInt(3, tarDeliverySN);
			ps.setInt(4, localDeplMainSN);
			ps.setInt(5, localSystemId);
			ps.setInt(6, targetSystemId);
			ps.setInt(7, 1);	//啟動交付中
			ps.execute();
			ps.close();
			
			//開始處理檔案
			for (int i=0;i<fod.getFiles().size();i++){
				String fn = fod.getFiles().get(i).getS2();	//部署檔
				if ( !"".equalsIgnoreCase( fn ) && fn!=null ) {
					String depFile = fod.getFiles().get(i).getS1();
					int detailId = i+1;
					int fileVer =  fod.getFiles().get(i).getI1();
					long fileSize = wid.getSVNfileSize(svnUrl, svnId, svnPwd, depFile, fileVer);
		    	    
					//	寫入部署細項<研究院>
					sql = "INSERT INTO depldetail (deplmainSN,depldetailid,localFile,isnonweb,localPath,depPath,localVer,depOrder,comReqsNum,creator,createdDateTime,fileSizeInByte) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(sql);
					ps.setInt(1, localDeplMainSN);		  	//deplmainSN
					ps.setInt(2, detailId);					//depldetailid
					ps.setString(3, depFile);				//localFile
					ps.setString(4, "t");					//isnonweb
					ps.setString(5, "");					//localPath
					ps.setString(6, "");					//depPath
					ps.setInt(7, fileVer);						//版次先寫0，等等簽入完再更新
					ps.setInt(8, 0);						//depOrder
					ps.setInt(9, fod.getReqs().size());		//comReqsNum
					ps.setString(10, empId);
					ps.setTimestamp(11, wid.cDT() );
					ps.setLong(12, fileSize);
					ps.execute();
					ps.close();
					
					//記錄SVN CM OL 與 分公司SVN的對應關係<研究院>
					int svnMappingSN = wid.getCurrentSN("delsvn");
					sql = "INSERT INTO delsvn (svnMappingSN,deliverySN,fromPath,fromFile,fromVer,toPath,toFile,toVer,sysSN,fromSVNhost,toSVNhost) VALUES ("+svnMappingSN+",?,?,?,?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(sql);
		    	    ps.setInt(1, deliverySN);				/*	交付方 交付代碼		*/											
		    	    ps.setString(2, "" );					/*	交付方	SVN相對路徑		*/
		    	    ps.setString(3, depFile );				/*	交付方 檔案名稱		*/
		    	    ps.setInt(4, fileVer );						/*	交付方	版次		*/
		    	    ps.setString(5, "" );					/*	接收方 SVN相對路徑		*/
		    	    ps.setString(6, depFile );				/*	接收方 檔案名稱		*/
		    	    ps.setLong(7, 0);						/*	接收方	版次		*/
		    	    ps.setInt(8, targetSystemId);			/*	交付端給了誰 (他給了誰)		*/
		    	    ps.setString(9, svnUrl );		/*	交付方 主機		*/
		    	    ps.setString(10, "" );					/*	接收方 主機		*/
		    	    ps.execute();
				}
			}
					
			
			String reqs = "<ul class='zhTwN req'>";
			
			// 寫入需求
			for (int i=0;i<fod.getReqs().size();i++){
				String reqSID = fod.getReqs().get(i).getReqSID();
				String reqDesc = fod.getReqs().get(i).getReqDesc();
				int reqStatus = wid.isReqExisted(reqSID, reqDesc);
				
				reqs += "<li>"+reqSID+"-"+reqDesc+"</li>";
				
				if( reqStatus == 3 ) {	//3 是不存在，所以要新增入需求的記錄中
					// 記錄需求<研究院>
					sql = "INSERT INTO reqs (reqDesc,reqSID,subsysId,creatorId,cDT,sysSN) VALUES (?,?,?,?,?,?)";
					ps = conn.prepareStatement(sql);
					ps.setString(1, reqDesc );
					ps.setString(2, reqSID );
					ps.setString(3, subsysId );
					ps.setString(4, empId );
					ps.setTimestamp(5, wid.cDT() );
					ps.setInt(6, localSystemId );
					ps.execute();
					ps.close();
				}
				sql = "SELECT reqId FROM reqs WHERE reqSID=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, reqSID );
				rs = ps.executeQuery();
				rs.next();
				int reqId = rs.getInt("reqId");
				
				for (int j=0;j<fod.getFiles().size();j++){
					String fn = fod.getFiles().get(j).getS2();	//部署檔
					if ( !"".equalsIgnoreCase( fn ) ) {
						int detailId = j+1;
						//記錄 需求所包含部署程式<研究院>
						sql = "INSERT INTO mpreqfiles (deplmainSN,depldetailid,reqSN,creator,createdDateTime) VALUES (?,?,?,?,?)";
						ps = conn.prepareStatement(sql);
						ps.setInt(1, localDeplMainSN );
						ps.setInt(2, detailId);
						ps.setInt(3, reqId);
						ps.setString(4, empId);
						ps.setTimestamp(5, wid.cDT() );
						ps.execute();
					}
				}
				rs.close();
			}
			reqs += "</ul>";
			msgBody += "需求：<br>"+reqs+"<p><p>Best regards<br>"+empName+"</font>";
			
			
			for (int j=0;j<fod.getFiles().size();j++){
				String fn = fod.getFiles().get(j).getS2();	//部署檔
				if ( !"".equalsIgnoreCase( fn ) ) {
					int detailId = j+1;
					//記錄 程式部署至Squad<研究院>
					sql = "INSERT INTO mpdeplunitsqu (deplmainSN,depldetailid,bssid,subsysId,squadId,creator,createdDateTime) VALUES(?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(sql);
					ps.setInt(1, localDeplMainSN );
					ps.setInt(2, detailId);
					ps.setString(3, "fOrder");
					ps.setString(4, subsysId);
					ps.setString(5, "SquadF_G");		//第一個squadId
					ps.setString(6, empId);
					ps.setTimestamp(7, wid.cDT() );
					ps.execute();
				}
			}

			//修改本地端交付事件的狀態	2 完成寄發通知待提領
			wid.updateDeltaskStatus(deliverySN, 2, wid.getConn());
			
			ArrayList<String[]> tos = wid.getRecipient(2, subsysId, "",targetSystemId );	//交付通知正本不需要知道
			ArrayList<String[]> ccs = wid.getRecipientCC(2, subsysId, "", localSystemId);
			ArrayList<String[]> bccs = new ArrayList<String[]>();
			//信件主旨
			String subject = localSystemName+"發起了交付 ("+deliverySN +")";
			wid.sendMailMain(tos,ccs,bccs,subject, msgBody);
			
		} catch(Exception e) {
			res = wid.errLog(e);
		} finally {
			try {
				if ( ins !=null ) {ins.close();}
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
				if ( souRepo!= null ) { souRepo.closeSession(); }
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		response.getWriter().write(res);
	
	}

}
